#pragma once

#include <iostream>
#include <time.h>
#include <stdarg.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <cstdlib>

using namespace std;

#define SIZE 1024
#define LogFile "log.txt" // 日志文件的名字

class Log // 使用方法 对象("info", 1,2,3,"sss")
{
public:
    Log()
    {
        printmethod = "Screen"; // 默认打印在屏幕上面
        path = "./mylog/";      // 默认路径
    }

    void Enable(string method)
    {
        printmethod = method;
    }

    void operator()(const string method, const char *format, ...)
    {
        time_t t = time(nullptr);
        struct tm *ctime = localtime(&t); // 返回一个指针

        char leftbuffer[SIZE];
        snprintf(leftbuffer, sizeof(leftbuffer), "[%s][%d-%d-%d %d:%d:%d]", method.c_str(), ctime->tm_year + 1900,
                 ctime->tm_mon + 1, ctime->tm_mday, ctime->tm_hour, ctime->tm_min, ctime->tm_sec);

        va_list s;
        va_start(s, format);

        char rightbuffer[SIZE];
        vsnprintf(rightbuffer, sizeof(rightbuffer), format, s); // 解析va_arg();的作用
        va_end(s);

        char logtxt[SIZE * 2+1];
        snprintf(logtxt, sizeof(logtxt), "%s %s\n", leftbuffer, rightbuffer);

        Printlog(printmethod, logtxt);
    }

    void Printlog(const string method, string logtxt)
    {

        if (method == "Screen")
        {
            cout << logtxt ;
        }
        else
        {
            string s = path + method + ".txt"; //./mylog/init.

            int fd = open(s.c_str(), O_WRONLY | O_CREAT | O_APPEND, 0666);
            if (fd < 0)
                return;
            write(fd, logtxt.c_str(), logtxt.size());
            close(fd);
        }
    }

private:
    string printmethod;
    string path;
};

Log lg;
